package cn.diancan.vo.other;
 
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List; 

public class ResultVoUtil {
	
    	/**
    	 * 将数据中用sql 读取的数据  自动填充到  model对象中
    	 * @param t
    	 * @param lsObj
    	 * @param hql
    	 * @return
    	 */
	public static <T> List<T> object2Model(Class<T> t , List<Object[]> lsObj,String hql){
		return object2Model(false,t,lsObj,hql);
	}
	
	/**
	 * 将数据中用sql 读取的数据  自动填充到  model对象中  
	 * @param isSpace  使用空格    " , "
	 * @param t
	 * @param lsObj
	 * @param hql
	 * @return
	 */
	public static <T> List<T> object2Model(boolean isSpace,Class<T> t, List<Object[]> lsObj,String hql){ 
		System.out.println(hql);
		if(null==lsObj || lsObj.size()<=0){
		    return new ArrayList<T>();
		}
		String hql2=  hql.split(" FROM ",2)[0];
		String[] param=null;
		if(isSpace){
			  param =  hql2.split(" , ");
		}else{
			  param =  hql2.split(",");
		}
		for (int i=0;i<param.length;i++) {
			 if(-1 != param[i].indexOf( " AS ")){//有别名
				 param[i]= param[i].split(" AS ")[1].trim();
			 }else if(-1 != param[i].indexOf(".")){
				 param[i]=param[i].split("\\.")[1].trim();
			 }else{
				 param[i]=param[i].trim();
				 if(-1  !=param[i].indexOf(" ")){
					 param[i] =param[i].split(" ")[1].trim();
				 }
			 }
		}
		
		List<T> list = new ArrayList<T>();
		for(Object[] ob : lsObj){
			T m =null;
			try {
				m = t.newInstance();
				for(int i=0 ;i< param.length ;i++ ){
					PropertyDescriptor proDescriptor = new PropertyDescriptor(param[i], m.getClass()); 
					Method methodSet = proDescriptor.getWriteMethod();
					Method methodget = proDescriptor.getReadMethod();
					Class<?> c= methodget.getReturnType();
					if(null !=  ob[i]){
						if("java.lang.String".equals(c.getName())){
							methodSet.invoke(m, ob[i].toString());
						}else if("java.lang.Integer".equals(c.getName()) || "int".equals(c.getName()) ){
							methodSet.invoke(m,(int)Integer.valueOf(ob[i].toString()) );
						}else if("java.lang.Double".equals(c.getName())  || "double".equals(c.getName())){
							methodSet.invoke(m,(double)Double.valueOf(ob[i].toString()) );
						}else if("java.lang.Float".equals(c.getName())  || "float".equals(c.getName())){
							methodSet.invoke(m,(float)Float.valueOf(ob[i].toString()));
						}else if("java.lang.Long".equals(c.getName()) || "long".equals(c.getName())){
							methodSet.invoke(m,(long)Long.valueOf(ob[i].toString()));
						}else{//如果都不是   抛异常
							throw new Exception("类型转换失败" );
						}
					}
				}
			} catch (Exception e) {
				System.out.println("类型转换 "+e.getMessage());
			} 
			list.add(m);
		}
		return list;
	}

}
